import uuid,datetime,os
from io import BytesIO
from fapiaopdf import cncurrency,crc16_x25
from makezip import InMemoryZIP
import qrcode
from PIL import Image
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.units import mm
import xml.sax.saxutils as saxutils
from decimal import Decimal   
        

def getQRcode(strs):
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_M,
        box_size=10,
        border=0,
    )
    # 添加数据
    qr.add_data(strs)
    # 填充数据
    qr.make(fit=True)
    # 生成图片
    img = qr.make_image(fill_color="black", back_color="white")
    img = img.convert("CMYK")  # RGBA
    # 添加logo
    icon = Image.open("png/shui.png")
    # 获取图片的宽高
    img_w, img_h = img.size
    
    factor = 6
    size_w = int(img_w / factor)
    size_h = int(img_h / factor)
    #icon_w, icon_h = icon.size
    #按百分比计算固定logo图片大小
    icon_w = int(0.268*img_w)
    icon_h = int(0.268*img_h)
    if icon_w > size_w:
        icon_w = size_w
    if icon_h > size_h:
        icon_h = size_h
    # 重新设置logo的尺寸
    icon = icon.resize((icon_w, icon_h), 4)
    w = int((img_w - icon_w) / 2)
    h = int((img_h - icon_h) / 2)
 
 
    img.paste(icon, (w, h), None)
    # 显示图片
    # plt.imshow(img)
    # plt.show()
    img = img.convert('RGB')
    buf = BytesIO()
    img.save(buf,'png')
    image_stream = buf.getvalue()
    buf.close()
    return image_stream

class InvoiceOFD:
    def __init__(self):
        self.ttf = TTFont('SIMSUN', 'ttfont\SIMSUN.TTC')
        self.id:int = 0
        self.template_ids:list = []
        self.templatePages_xml_str = ""
        self.pages_xml_str = ""
        self.qcodepng_id:int = 0
        self.zhangpng_id:int = 0
        self.StrokeColor_id:int = 0
        self.ColorSpace_id:int = 0
        self.FillColor_id:int = 0
        self.fontkaiti_id:int = 0
        self.fontsongti_id:int = 0
        self.fontCourierNew_id:int = 0
        self.page_count:int = 1
    
    def parsedeltaX(self,s,size=3.175):
        #print(size*mm)
        #size = size*mm
        dls = [0]
        dxs = []
        deltaX = []
        s_len = len(s)
        for i in range(0,s_len):
            if not dxs:
                dxs.append(self.ttf.stringWidth(s[i],size))
                dls[len(dls)-1] +=1
            else:
                if self.ttf.stringWidth(s[i],size)==dxs[len(dxs)-1]:
                    dls[len(dls)-1] +=1
                else:
                    dxs.append(self.ttf.stringWidth(s[i],size))
                    dls.append(0)
                    dls[len(dls)-1] +=1
        for i in range(0,len(dxs)):
            if dls==1:
                deltaX.append(str(dxs[i]))
            else:
                deltaX += ['g',str(dls[i]),str(dxs[i])]
        return ' '.join(deltaX)

    def gerdl(self,s,width):
        dls = ['']
        s_len = len(s)
        for i in range(0,s_len):        
            dls[len(dls)-1] +=s[i]
            if i<s_len-1:
                ss = dls[len(dls)-1]+s[i+1]
                if self.ttf.stringWidth(ss,9)>width:
                    dls.append('')    
        return dls
    
    def get_centered_y(self,s,width,size=3.175):
        return width/2-self.ttf.stringWidth(s,size)/2
    
    def get_right_x(self,s,width,size=3.175):
        return width-self.ttf.stringWidth(s,size)

    def _getid(self):
        self.id = 1+self.id
        return self.id

    def makedocumentxml(self):
        
        document_xml_str = f"""<?xml version="1.0" encoding="UTF-8"?>
    <ofd:Document xmlns:ofd="http://www.ofdspec.org/2016">
      <ofd:CommonData>
        <ofd:MaxUnitID>{self._getid()}</ofd:MaxUnitID>
        <ofd:PublicRes>PublicRes.xml</ofd:PublicRes>
        {self.templatePages_xml_str}
      <ofd:DocumentRes>DocumentRes.xml</ofd:DocumentRes></ofd:CommonData>
      <ofd:Pages>{self.pages_xml_str}</ofd:Pages>	
      </ofd:Document>"""
        return document_xml_str.encode()

    def maketemplate(self,data,py=0,islast=True):
        title_xml_str = ''
        match data['KPLX']:
            case '31':
                title_xml_str = f"""<ofd:TextObject ID="{self._getid()}" Boundary="56 8 90 7.0732" Size="7.0732" Font="{self.fontkaiti_id}">
            <ofd:TextCode Y="6.0854" X="1.061" DeltaX="g 11 7.0696">电子发票（增值税专用发票）</ofd:TextCode>
          </ofd:TextObject>"""
            case '32':
                title_xml_str=f"""<ofd:TextObject ID="{self._getid()}" Boundary="67 8 68.803 7.0732" Font="{self.fontkaiti_id}" Size="7.0732">
          <ofd:TextCode X="1.061" Y="6.0854" DeltaX="7.0696 7.1118 g 2 7.0696 7.1118 g 2 7.0696 7.1118 7.0696">电子发票（普通发票）</ofd:TextCode>
        </ofd:TextObject>"""
        islast_xml_str = ''
        if islast:
            islast_xml_str = f"""<ofd:PathObject ID="{self._getid()}" Boundary="4.5 {103.8+py} 201 0.4">
            <ofd:AbbreviatedData>M 0 0.2 L 201 0.2</ofd:AbbreviatedData>
          </ofd:PathObject>
          <ofd:PathObject ID="{self._getid()}" Boundary="4.5 {95.8+py} 201 0.4">
            <ofd:AbbreviatedData>M 0 0.2 L 201 0.2</ofd:AbbreviatedData>
          </ofd:PathObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="16.4068 {98.5+py} 27.1255 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="3.175 3.175 g 2 3.175 3.175 g 2 3.175">价税合计（大写）</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="143 {98.5+py} 19 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="3.175 3.175 3.175">（小写）</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="5.5 {109+py} 4.4926 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163">备</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="5.5 {115+py} 4.2633 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163">注</ofd:TextCode>
          </ofd:TextObject>
          <ofd:PathObject ID="{self._getid()}" Boundary="10.5 {104+py} 0.4 20">
            <ofd:AbbreviatedData>M 0.2 0 L 0.2 20</ofd:AbbreviatedData>
          </ofd:PathObject>
          <ofd:PathObject ID="{self._getid()}" Boundary="56.3 {96+py} 0.4 8">
            <ofd:AbbreviatedData>M 0.2 0 L 0.2 8</ofd:AbbreviatedData>
          </ofd:PathObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="20 {92+py} 4.5808 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163">合</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="36 {92+py} 4.2986 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163">计</ofd:TextCode>
          </ofd:TextObject>"""
        else:
            islast_xml_str = f"""<ofd:TextObject ID="{self._getid()}" Boundary="20 {120+py} 60 3.5101" Font="{self.fontkaiti_id}" Size="3.175">
				<ofd:TextCode X="0.5265" Y="3.0163" DeltaX="16">合计</ofd:TextCode>
			</ofd:TextObject>
			<ofd:TextObject ID="{self._getid()}" Boundary="20 {115+py} 60 3.5101" Font="{self.fontkaiti_id}" Size="3.175">
				<ofd:TextCode X="0.5265" Y="3.0163" DeltaX="16">小计</ofd:TextCode>
			</ofd:TextObject>"""
        template_xml_str = f"""<?xml version="1.0" encoding="UTF-8"?>
    <ofd:Page xmlns:ofd="http://www.ofdspec.org/2016">
      <ofd:Area>
        <ofd:PhysicalBox>0 0 210 {140+py}</ofd:PhysicalBox>
      </ofd:Area>
      <ofd:Content>
        <ofd:Layer ID="{self._getid()}">
          <!--打印识别线-->
          <ofd:PathObject ID="{self._getid()}" Boundary="205.6 29.8 0.54 {47+py/2}" LineWidth="0.54" Join="Bevel">
            <ofd:StrokeColor Value="246 237 225" ColorSpace="{self.ColorSpace_id}"/>
            <ofd:AbbreviatedData>M 0.254 0.254 L 0.254 {47+py/2}</ofd:AbbreviatedData>
          </ofd:PathObject>
          <ofd:PathObject ID="{self._getid()}" Boundary="205.6 {76.6+py/2} 0.54 {47+py/2}" LineWidth="0.54" Join="Bevel">
            <ofd:StrokeColor Value="118 89 84" ColorSpace="{self.ColorSpace_id}"/>
            <ofd:AbbreviatedData>M 0.254 0.254 L 0.254 {47+py/2}</ofd:AbbreviatedData>
          </ofd:PathObject>
        </ofd:Layer>
        <ofd:Layer ID="{self._getid()}" DrawParam="{self.FillColor_id}">
          <!--73mm线-->
          <ofd:PathObject ID="{self._getid()}" Boundary="65.5 17.8 73 0.4">
            <ofd:AbbreviatedData>M 0 0.2 L 73 0.2</ofd:AbbreviatedData>
          </ofd:PathObject>
          <ofd:PathObject ID="{self._getid()}" Boundary="65.5 18.8 73 0.4">
            <ofd:AbbreviatedData>M 0 0.2 L 73 0.2</ofd:AbbreviatedData>
          </ofd:PathObject>
          <!--201mm线-->
          <ofd:PathObject ID="{self._getid()}" Boundary="4.5 29.8 201 0.4">
            <ofd:AbbreviatedData>M 0 0.2 L 201 0.2</ofd:AbbreviatedData>
          </ofd:PathObject>
          <ofd:PathObject ID="{self._getid()}" Boundary="4.5 51.8 201 0.4">
            <ofd:AbbreviatedData>M 0 0.2 L 201 0.2</ofd:AbbreviatedData>
          </ofd:PathObject>                    
          <ofd:PathObject ID="{self._getid()}" Boundary="4.5 {123.8+py} 201 0.4">
            <ofd:AbbreviatedData>M 0 0.2 L 201 0.2</ofd:AbbreviatedData>
          </ofd:PathObject>
          <!--94线-->
          <ofd:PathObject ID="{self._getid()}" Boundary="4.3 30 0.4 {94+py}">
            <ofd:AbbreviatedData>M 0.2 0 L 0.2 {94+py}</ofd:AbbreviatedData>
          </ofd:PathObject>
          <ofd:PathObject ID="{self._getid()}" Boundary="205.3 30 0.4 {94+py}">
            <ofd:AbbreviatedData>M 0.2 0 L 0.2 {94+py}</ofd:AbbreviatedData>
          </ofd:PathObject>
          <!--22线-->
          <ofd:PathObject ID="{self._getid()}" Boundary="10.5 30 0.4 22">
            <ofd:AbbreviatedData>M 0.2 0 L 0.2 22</ofd:AbbreviatedData>
          </ofd:PathObject>
          <ofd:PathObject ID="{self._getid()}" Boundary="105 30 0.4 22">
            <ofd:AbbreviatedData>M 0.2 0 L 0.2 22</ofd:AbbreviatedData>
          </ofd:PathObject>
          <ofd:PathObject ID="{self._getid()}" Boundary="111 30 0.4 22">
            <ofd:AbbreviatedData>M 0.2 0 L 0.2 22</ofd:AbbreviatedData>
          </ofd:PathObject>          
          {title_xml_str}
          <ofd:TextObject ID="{self._getid()}" Boundary="154 11 16.2605 3.175" Font="{self.fontkaiti_id}" Size="3.3">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="3.175 3.175 g 2 3.175">发票号码：</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="154 17 16.2605 3.175" Font="{self.fontkaiti_id}" Size="3.3">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="3.175 3.175 g 2 3.175">开票日期：</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" CTM="0.89 0 0 1 0 0" Boundary="5.5 32.5 3.9182 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163">购</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" CTM="0.89 0 0 1 0 0" Boundary="5.5 36 3.6889 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163">买</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" CTM="0.89 0 0 1 0 0" Boundary="5.5 39.5 3.9711 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163">方</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" CTM="0.89 0 0 1 0 0" Boundary="5.5 43 3.8476 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163">信</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" CTM="0.89 0 0 1 0 0" Boundary="5.5 46.5 3.83 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163">息</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" CTM="0.89 0 0 1 0 0" Boundary="11 44 67.5 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="g 8 3.175 1.6 g 4 3.175">统一社会信用代码/纳税人识别号：</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" CTM="0.89 0 0 1 0 0" Boundary="106 32.5 3.7771 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163">销</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" CTM="0.89 0 0 1 0 0" Boundary="106 36 3.7771 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163">售</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" CTM="0.89 0 0 1 0 0" Boundary="106 39.5 3.9711 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163">方</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" CTM="0.89 0 0 1 0 0" Boundary="106 43 3.8476 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163">信</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" CTM="0.89 0 0 1 0 0" Boundary="106 46.5 3.83 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163">息</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" CTM="0.89 0 0 1 0 0" Boundary="111.5 44 67.5 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="g 8 3.175 1.6 g 4 3.175">统一社会信用代码/纳税人识别号：</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="11 33.5 16 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="3.175 3.175">名称：</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="111.5 33.5 16 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="3.175 3.175">名称：</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="15.5 53 14.8814 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="3.175 3.175 3.175">项目名称</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="41.6 53 14.8814 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="3.175 3.175 3.175">规格型号</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="66.5 53 10 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="3.175">单 位</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="92.5 53 10 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="3.175">数 量</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="117.5 53 10 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="3.175">单 价</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="143 53 10 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="3.175">金 额</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="157 53 60 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="3.175 3.175 1.6 3.175 3.175">税率/征收率</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="194 53 10 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="3.175">税 额</ofd:TextCode>
          </ofd:TextObject>
          {islast_xml_str}
          <ofd:TextObject ID="{self._getid()}" Boundary="19 {129.5+py} 19 3.3" Font="{self.fontkaiti_id}" Size="3.175">
            <ofd:TextCode X="0.5265" Y="3.0163" DeltaX="g 3 3.175">开票人：</ofd:TextCode>
          </ofd:TextObject>
        </ofd:Layer>
      </ofd:Content>
    </ofd:Page>
    """
        return template_xml_str.encode()

    def makedocumentres(self):
        self.qcodepng_id = self._getid()
        self.zhangpng_id = self._getid()
        document_res_xml_str = f"""<?xml version="1.0" encoding="UTF-8"?>
    <ofd:Res xmlns:ofd="http://www.ofdspec.org/2016" BaseLoc="Res">
      <ofd:MultiMedias>
        <ofd:MultiMedia ID="{self.qcodepng_id}" Type="Image">
          <ofd:MediaFile>image_{self.qcodepng_id}.png</ofd:MediaFile>
        </ofd:MultiMedia>
        <ofd:MultiMedia ID="{self.zhangpng_id}" Type="Image" Format="PNG">
          <ofd:MediaFile>image_{ self.zhangpng_id}.png</ofd:MediaFile>
        </ofd:MultiMedia>
      </ofd:MultiMedias>
    </ofd:Res>"""
        return document_res_xml_str.encode()

    #字体资源文件生成
    def makepublicres(self):
        self.ColorSpace_id = self._getid()
        self.StrokeColor_id = self._getid()
        self.FillColor_id = self._getid()
        self.fontkaiti_id = self._getid()
        self.fontsongti_id = self._getid()
        self.fontCourierNew_id = self._getid()
        pulic_res_str = f"""<?xml version="1.0" encoding="UTF-8"?>
    <ofd:Res xmlns:ofd="http://www.ofdspec.org/2016">
      <ofd:ColorSpaces>
        <ofd:ColorSpace ID="{self.ColorSpace_id}" Type="RGB"/>
      </ofd:ColorSpaces>
      <ofd:DrawParams>
        <ofd:DrawParam ID="{self.StrokeColor_id}" LineWidth="0.25">
          <ofd:StrokeColor Value="128 0 0" ColorSpace="{self.ColorSpace_id}"/>
        </ofd:DrawParam>
        <ofd:DrawParam ID="{self.FillColor_id}" Relative="{self.StrokeColor_id}">
          <ofd:FillColor Value="128 0 0" ColorSpace="{self.ColorSpace_id}"/>
        </ofd:DrawParam>
      </ofd:DrawParams>
      <ofd:Fonts>
        <ofd:Font ID="{self.fontkaiti_id}" FontName="楷体" FamilyName="楷体"/>
        <ofd:Font ID="{self.fontsongti_id}" FontName="宋体" FamilyName="SimSun"/>
        <ofd:Font ID="{self.fontCourierNew_id}" FontName="Courier New"/>
      </ofd:Fonts>
    </ofd:Res>"""
        return pulic_res_str.encode()

    def makeofdxml(self,data):
        str_now = datetime.datetime.now().strftime('%Y-%m-%d')
        ofd_xml_str = f"""<?xml version="1.0" encoding="UTF-8"?>
    <ofd:OFD xmlns:ofd="http://www.ofdspec.org/2016" DocType="OFD" Version="1.0">
      <ofd:DocBody>
        <ofd:DocInfo>
          <ofd:DocID>{uuid.uuid4().hex}</ofd:DocID>
          <ofd:Author>申南爱信诺</ofd:Author>
          <ofd:CreationDate>{str_now}</ofd:CreationDate>
          <ofd:ModDate>{str_now}</ofd:ModDate>
          <ofd:Creator>sn</ofd:Creator>
          <ofd:CustomDatas>
            <ofd:CustomData Name="template-version">1.0.20.0422</ofd:CustomData>
            <ofd:CustomData Name="发票号码"> {data.get('FPHM')}</ofd:CustomData>
            <ofd:CustomData Name="销售方纳税人识别号">{data.get('XHFSBH')}</ofd:CustomData>
            <ofd:CustomData Name="合计金额">{data.get('HJ')}</ofd:CustomData>
            <ofd:CustomData Name="购买方纳税人识别号">{data.get('GGFSBH')}</ofd:CustomData>
            <ofd:CustomData Name="合计税额">{data.get('HJSE')}</ofd:CustomData>
            <ofd:CustomData Name="开票日期">{data.get('KPRQ')}</ofd:CustomData>
            <ofd:CustomData Name="producer-version">2.0.23.1108.1400</ofd:CustomData>
          </ofd:CustomDatas>
        </ofd:DocInfo>
        <ofd:DocRoot>Doc_0/Document.xml</ofd:DocRoot>
      </ofd:DocBody>
    </ofd:OFD>"""
        return ofd_xml_str.encode()

    def makepagecontent(self,data,py=0,pageidx=0,islast=True,):
        page_number_xml_str= ''
        if self.page_count>1:
            page_number_str = f"""共{self.page_count}页 第{pageidx+1}页"""
            page_number_xml_str =f"""<ofd:TextObject ID="{self._getid()}" Size="3.175" Font="{self.fontsongti_id}" Boundary="164.7733 24.5 39.937 5.2894">
      <ofd:TextCode DeltaX="{self.parsedeltaX(page_number_str)}" Y="3.7861" X="{self.get_right_x(page_number_str,39.937)}">{page_number_str}</ofd:TextCode>
    </ofd:TextObject>"""
        table_xmls = []
        xiaoji = Decimal('0.00')
        xiaojise = Decimal('0.00')
        for i,item in enumerate(data['datas']):
            line_h = 4.5*i
            txl_strs = []
            if item['ItemName']:
                txl_strs.append(f"""<ofd:TextObject ID="{self._getid()}" Boundary="4.5 {56+line_h} 36.5 4.5" Font="{self.fontsongti_id}" Size="3.175">
  <ofd:TextCode X="0" Y="3.2571" DeltaX="{self.parsedeltaX(item['ItemName'])}">{saxutils.escape(item['ItemName'])}</ofd:TextCode>
</ofd:TextObject>""")
            if item['SpecMod']:
                txl_strs.append(f"""<ofd:TextObject ID="{self._getid()}" Boundary="42 {56+line_h} 23.5 4.5" Font="{self.fontsongti_id}" Size="3.175">
  <ofd:TextCode X="0" Y="3.3914" DeltaX="{self.parsedeltaX(item['SpecMod'])}">{saxutils.escape(item['SpecMod'])}</ofd:TextCode>
</ofd:TextObject>""")
            if item['MeaUnits']:
                txl_strs.append(f"""<ofd:TextObject ID="{self._getid()}" Boundary="65.5 {56+line_h} 12 4.5" Font="{self.fontsongti_id}" Size="3.175">
  <ofd:TextCode X="{self.get_centered_y(item['MeaUnits'],12)}" Y="3.3914" DeltaX="{self.parsedeltaX(item['MeaUnits'])}">{saxutils.escape(item['MeaUnits'])}</ofd:TextCode>
</ofd:TextObject>""")
            if item['Quantity']:
                txl_strs.append(f"""<ofd:TextObject ID="{self._getid()}" Size="3.175" Font="{self.fontsongti_id}" Boundary="77.5 {56+line_h} 25 4.5">
  <ofd:TextCode DeltaX="{self.parsedeltaX(item['Quantity'])}" Y="3.3914" X="{self.get_right_x(item['Quantity'],25)}">{saxutils.escape(item['Quantity'])}</ofd:TextCode>
</ofd:TextObject>""")
            if item['UnPrice']:
                table_xmls.append(f"""<ofd:TextObject ID="{self._getid()}" Boundary="102.5 {56+line_h} 25 4.5" Font="{self.fontsongti_id}" Size="3.175">
  <ofd:TextCode X="{self.get_right_x(item['UnPrice'],25)}" Y="3.3914" DeltaX="{self.parsedeltaX(item['UnPrice'])}">{saxutils.escape(item['UnPrice'])}</ofd:TextCode>
</ofd:TextObject>""")
            if item['Amount']:
                txl_strs.append(f"""<ofd:TextObject ID="{self._getid()}" Boundary="127.5 {56+line_h} 25.5 4.5" Font="{self.fontsongti_id}" Size="3.175">
  <ofd:TextCode X="{self.get_right_x(item['Amount'],25.5)}" Y="3.3914" DeltaX="{self.parsedeltaX(item['Amount'])}">{saxutils.escape(item['Amount'])}</ofd:TextCode>
</ofd:TextObject>""")                
            if item['TaxRate']:
                txl_strs.append(f"""<ofd:TextObject ID="{self._getid()}" Boundary="154 {56+line_h} 25 4.5" Font="{self.fontsongti_id}" Size="3.175">
  <ofd:TextCode X="{self.get_centered_y(item['TaxRate'],25)}" Y="3.3914" DeltaX="{self.parsedeltaX(item['TaxRate'])}">{saxutils.escape(item['TaxRate'])}</ofd:TextCode>
</ofd:TextObject>""")           
            if item['ComTaxAm']:
                table_xmls.append(f"""<ofd:TextObject ID="{self._getid()}" Boundary="179.5 {56+line_h} 26 4.5" Font="{self.fontsongti_id}" Size="3.175">
  <ofd:TextCode X="{self.get_right_x(item['ComTaxAm'],26)}" Y="3.2567" DeltaX="{self.parsedeltaX(item['ComTaxAm'])}">{saxutils.escape(item['ComTaxAm'])}</ofd:TextCode>
</ofd:TextObject>""")               
            table_xmls.append(''.join(txl_strs))
            if item['Amount']:
                xiaoji += Decimal(item['Amount']) 
            if item['ComTaxAm']:
                xiaojise += Decimal(item['ComTaxAm'])
        str_xiaoji = '%.2f' %xiaoji
        str_xiaojise = '%.2f' %xiaojise
        islast_xml_str = ''
        bz_xml_strs = []
        if islast:
            bzs = data['BZ'].split('/r/n')#先按换行符分割
            bz_i = 0
            for bs in bzs:
                for p in self.gerdl(bs,193*mm):
                    bz_xml_strs.append(f"""<ofd:TextObject ID="{self._getid()}" Size="3.175" Font="{self.fontsongti_id}" Boundary="11.1083 {107.8369+py+3.3*bz_i} 193 3.3">
            <ofd:TextCode DeltaX="{self.parsedeltaX(p)}" Y="2.7273" X="0">{saxutils.escape(p)}</ofd:TextCode>
          </ofd:TextObject>""")
                    bz_i += 1
            islast_xml_str = f"""<ofd:PathObject ID="{self._getid()}" Boundary="57.9471 {97+py} 5 5" LineWidth="0.225" Fill="true">
            <ofd:AbbreviatedData>M 4.5315 2.493 B 4.5315 1.368 3.618 0.45 2.4885 0.45 B 1.3635 0.45 0.45 1.368 0.45 2.493 B 0.45 3.618 1.3635 4.536 2.4885 4.536 B 3.618 4.536 4.5315 3.618 4.5315 2.493 M 1.035 1.035 L 3.915 3.915 M 1.035 3.915 L 3.915 1.035 </ofd:AbbreviatedData>
          </ofd:PathObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="62.9471 {96+py} 82.5189 7.4102" Font="{self.fontsongti_id}" Size="3.175">
            <ofd:TextCode X="0" Y="4.8465" DeltaX="{self.parsedeltaX(cncurrency(data['JSHJ']))}">{cncurrency(data['JSHJ'])}</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="155.5164 {96.0681+py} 48.665 7.6749" Font="{self.fontCourierNew_id}" Size="3.8806">
            <ofd:TextCode X="0" Y="4.9221">¥</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="155.5164 {96.0681+py} 48.665 7.6749" Font="{self.fontsongti_id}" Size="3.8806">
            <ofd:TextCode X="2.3284" Y="4.9221" DeltaX="g 5 1.9403">{data['JSHJ']}</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="127.5 {90.5+py} 26 5.293" Font="{self.fontCourierNew_id}" Size="3.8806">
            <ofd:TextCode X="{self.get_right_x(data['HJ'],26)-2.3284}" Y="4.1288">¥</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="127.5 {90.5+py} 26 5.293" Font="{self.fontsongti_id}" Size="3.175">
            <ofd:TextCode X="{self.get_right_x(data['HJ'],26)}" Y="4.1288" DeltaX="{self.parsedeltaX(data['HJ'])}">{data['HJ']}</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="179.5 {90.5+py} 26 5.293" Font="{self.fontCourierNew_id}" Size="3.8806">
            <ofd:TextCode X="{self.get_right_x(data['HJSE'],26)-2.3284}" Y="4.1288">¥</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="179.5 {90.5+py} 26 5.293" Font="{self.fontsongti_id}" Size="3.175">
            <ofd:TextCode X="{self.get_right_x(data['HJSE'],26)}" Y="4.1288" DeltaX="{self.parsedeltaX(data['HJSE'])}">{data['HJSE']}</ofd:TextCode>
          </ofd:TextObject>{''.join(bz_xml_strs)}"""
        else:
            islast_xml_str = f"""<ofd:TextObject ID="{self._getid()}" Boundary="127.5 {118.5+py} 26 5.293" Font="{self.fontCourierNew_id}" Size="3.8806">
            <ofd:TextCode X="{self.get_right_x(data['HJ'],26)-2.3284}" Y="4.1288">¥</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="127.5 {118.5+py} 26 5.293" Font="{self.fontsongti_id}" Size="3.175">
            <ofd:TextCode X="{self.get_right_x(data['HJ'],26)}" Y="4.1288" DeltaX="{self.parsedeltaX(data['HJ'])}">{data['HJ']}</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="179.5 {118.5+py} 26 5.293" Font="{self.fontCourierNew_id}" Size="3.8806">
            <ofd:TextCode X="{self.get_right_x(data['HJSE'],26)-2.3284}" Y="4.1288">¥</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="179.5 {118.5+py} 26 5.293" Font="{self.fontsongti_id}" Size="3.175">
            <ofd:TextCode X="{self.get_right_x(data['HJSE'],26)}" Y="4.1288" DeltaX="{self.parsedeltaX(data['HJSE'])}">{data['HJSE']}</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="127.5 {113.5+py} 26 5.293" Font="{self.fontCourierNew_id}" Size="3.8806">
            <ofd:TextCode X="{self.get_right_x(str_xiaoji,26)-2.3284}" Y="4.1288">¥</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="127.5 {113.5+py} 26 5.293" Font="{self.fontsongti_id}" Size="3.175">
            <ofd:TextCode X="{self.get_right_x(str_xiaoji,26)}" Y="4.1288" DeltaX="{self.parsedeltaX(str_xiaoji)}">{str_xiaoji}</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="179.5 {113.5+py} 26 5.293" Font="{self.fontCourierNew_id}" Size="3.8806">
            <ofd:TextCode X="{self.get_right_x(str_xiaojise,26)-2.3284}" Y="4.1288">¥</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="179.5 {113.5+py} 26 5.293" Font="{self.fontsongti_id}" Size="3.175">
            <ofd:TextCode X="{self.get_right_x(str_xiaojise,26)}" Y="4.1288" DeltaX="{self.parsedeltaX(str_xiaojise)}">{str_xiaojise}</ofd:TextCode>
          </ofd:TextObject>"""

        content_xml_str = f"""<?xml version="1.0" encoding="UTF-8"?>
    <ofd:Page xmlns:ofd="http://www.ofdspec.org/2016">
      <ofd:Area>
        <ofd:PhysicalBox>0 0 210 {140+py}</ofd:PhysicalBox>
      </ofd:Area>
      <ofd:Template TemplateID="{self.template_ids[pageidx]}" ZOrder="Background"/>
      <ofd:Content>
        <ofd:Layer ID="{self._getid()}">
          <ofd:TextObject ID="{self._getid()}" Boundary="170 10.3 38 5" Font="{self.fontsongti_id}" Size="3.175">
            <ofd:TextCode X="0" Y="3.6414" DeltaX="g 19 1.5875">{data.get('FPHM')}</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="170 16.4 38 5" Font="{self.fontsongti_id}" Size="3.175">
            <ofd:TextCode X="0" Y="3.6414" DeltaX="g 4 1.5875 3.175 g 2 1.5875 3.175 g 2 1.5875">{data.get('KPRQ')}</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="20 33.8 84 10.8" Font="{self.fontsongti_id}" Size="3.175">
            <ofd:TextCode X="0" Y="2.7273" DeltaX="{self.parsedeltaX(data.get('GGFMC'),3.175)}">{saxutils.escape(data.get('GGFMC'))}</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="54 43.3 58 5.293" Font="{self.fontCourierNew_id}" Size="4.2333">
            <ofd:TextCode X="0" Y="3.7726" DeltaX="g 17 2.54">{saxutils.escape(data.get('GGFSBH'))}</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="120 33.8 84 10.8" Font="{self.fontsongti_id}" Size="3.175">
            <ofd:TextCode X="0" Y="2.7273" DeltaX="{self.parsedeltaX(data.get('XHFMC'),3.175)}">{data.get('XHFMC')}</ofd:TextCode>
          </ofd:TextObject>
          <ofd:TextObject ID="{self._getid()}" Boundary="154.5 43.3 58 5.293" Font="{self.fontCourierNew_id}" Size="4.2333">
            <ofd:TextCode X="0" Y="3.7726" DeltaX="g 17 2.54">{data.get('XHFSBH')}</ofd:TextCode>
          </ofd:TextObject>
          {''.join(table_xmls)}{islast_xml_str}
          <ofd:TextObject ID="{self._getid()}" Boundary="32.0025 {129.1+py} 150 4.7637" Font="{self.fontsongti_id}" Size="3.175">
            <ofd:TextCode X="0" Y="3.5233" DeltaX="{self.parsedeltaX(data['KPR'])}">{saxutils.escape(data.get('KPR'))}</ofd:TextCode>
          </ofd:TextObject>{page_number_xml_str}
          <ofd:ImageObject ID="{self._getid()}" CTM="20 0 0 20 0 0" Boundary="6.5 6 20 20" ResourceID="{self.qcodepng_id}"/>
          <ofd:ImageObject ID="{self._getid()}" BlendMode="Darken" CTM="30 0 0 20 0 0" Boundary="90 8 30 20" ResourceID="{self.zhangpng_id}">
        </ofd:Layer>
      </ofd:Content>
    </ofd:Page>"""
        
        return content_xml_str.encode()
        
    def makeofd(self,data,qianzhangpng):
        listdata = data['datas']
        newlistdata = []
        for item in listdata:
            ItemNames = self.gerdl(item['ItemName'],37*mm-2)
            SpecMods = self.gerdl(item['SpecMod'],24*mm-2)
            if len(ItemNames) >= len(SpecMods):
                for i,itemName in enumerate(ItemNames):
                    newlistdata.append({
                        'ItemName':itemName,
                        'SpecMod':SpecMods[i] if i<len(SpecMods) else '',
                        'MeaUnits':item['MeaUnits'] if i==0 else '',
                        'Quantity':item['Quantity'] if i==0 else '',
                        'UnPrice':item['UnPrice'] if i==0 else '',
                        'Amount':item['Amount'] if i==0 else '',
                        'TaxRate':item['TaxRate'] if i==0 else '',
                        'ComTaxAm':item['ComTaxAm'] if i==0 else ''
                    })
            else:
                for i,specMod in enumerate(SpecMods):
                    newlistdata.append({
                        'ItemName':ItemNames[i] if i<len(ItemNames) else '',
                        'SpecMod':specMod,
                        'MeaUnits':item['MeaUnits'] if i==0 else '',
                        'Quantity':item['Quantity'] if i==0 else '',
                        'UnPrice':item['UnPrice'] if i==0 else '',
                        'Amount':item['Amount'] if i==0 else '',
                        'TaxRate':item['TaxRate'] if i==0 else '',
                        'ComTaxAm':item['ComTaxAm'] if i==0 else ''
                    })
        #print(len(newlistdata))
        
        #按照行数计算高度超过分割pdf页
        def split_array(arr, chunk_size):
            return [arr[i:i + chunk_size] for i in range(0, len(arr), chunk_size)]
        newlistdatas = split_array(newlistdata,47)
        self.page_count = len(newlistdatas)
        if len(newlistdatas[len(newlistdatas)-1])>42:
            self.page_count = self.page_count+1
        imz = InMemoryZIP()
        imz.append('Doc_0/DocumentRes.xml',self.makedocumentres())
        imz.append('Doc_0/PublicRes.xml',self.makepublicres())
        templatePages = []
        pages = []
        qstrs = [
            '01',
            data['KPLX'],
            '',
            data["FPHM"],
            data["JSHJ"],
            data["KPRQ"].replace('年','').replace('月','').replace('日',''),
            '',   
        ]
        crc_str = hex(crc16_x25(','.join(qstrs).encode()))
        qstrs.append(crc_str[2:])
        qstr = ",".join(qstrs)
        qimg = getQRcode(qstr)
        imz.append(f'Doc_0/Res/image_{self.qcodepng_id}.png',qimg)
        zhangpng = f'png/{qianzhangpng}.png'
        imz.appendfile(zhangpng,f'Doc_0/Res/image_{self.zhangpng_id}.png')
        indexpy = 0
        for i,_newlistdata in enumerate(newlistdatas):
            index = i+indexpy
            template_id = self._getid()
            self.template_ids.append(template_id)
            templatePages.append(f"""<ofd:TemplatePage ID="{template_id}" BaseLoc="Tpls/Tpl_{i+indexpy}/Content.xml"/>""")
            pages.append(f"""<ofd:Page ID="{self._getid()}" BaseLoc="Pages/Page_{i+indexpy}/Content.xml"/>""")
            #print(len(_newlistdata))
            islast = False
            if index == len(newlistdatas) - 1:
                islast = True
            if len(_newlistdata) > 8 and len(_newlistdata) <= 12:
                data['datas'] = _newlistdata
                imz.append(f'Doc_0/Tpls/Tpl_{index}/Content.xml',self.maketemplate(data=data,py=17.5,islast=islast))
                imz.append(f'Doc_0/Pages/Page_{index}/Content.xml',self.makepagecontent(data=data,py=17.5,pageidx=index,islast=islast))
            elif len(_newlistdata) > 12 and len(_newlistdata) <= 16:
                data['datas'] = _newlistdata
                imz.append(f'Doc_0/Tpls/Tpl_{index}/Content.xml',self.maketemplate(data=data,py=17.5*2,islast=islast))
                imz.append(f'Doc_0/Pages/Page_{index}/Content.xml',self.makepagecontent(data=data,py=17.5*2,pageidx=index,islast=islast))
            elif len(_newlistdata) > 16 and len(_newlistdata) <= 20:
                data['datas'] = _newlistdata
                imz.append(f'Doc_0/Tpls/Tpl_{index}/Content.xml',self.maketemplate(data=data,py=17.5*3,islast=islast))
                imz.append(f'Doc_0/Pages/Page_{index}/Content.xml',self.makepagecontent(data=data,py=17.5*3,pageidx=index,islast=islast))
            elif len(_newlistdata) > 20 and len(_newlistdata) <= 24:
                data['datas'] = _newlistdata
                imz.append(f'Doc_0/Tpls/Tpl_{index}/Content.xml',self.maketemplate(data=data,py=17.5*4,islast=islast))
                imz.append(f'Doc_0/Pages/Page_{index}/Content.xml',self.makepagecontent(data=data,py=17.5*4,pageidx=index,islast=islast))
            elif len(_newlistdata) > 24 and len(_newlistdata) <= 28:
                data['datas'] = _newlistdata
                imz.append(f'Doc_0/Tpls/Tpl_{index}/Content.xml',self.maketemplate(data=data,py=17.5*5,islast=islast))
                imz.append(f'Doc_0/Pages/Page_{index}/Content.xml',self.makepagecontent(data=data,py=17.5*5,pageidx=index,islast=islast))
            elif len(_newlistdata) > 28 and len(_newlistdata) <= 32:
                data['datas'] = _newlistdata
                imz.append(f'Doc_0/Tpls/Tpl_{index}/Content.xml',self.maketemplate(data=data,py=17.5*6,islast=islast))
                imz.append(f'Doc_0/Pages/Page_{index}/Content.xml',self.makepagecontent(data=data,py=17.5*6,pageidx=index,islast=islast))
            elif len(_newlistdata) > 32 and len(_newlistdata) <= 36:
                data['datas'] = _newlistdata
                imz.append(f'Doc_0/Tpls/Tpl_{index}/Content.xml',self.maketemplate(data=data,py=17.5*7,islast=islast))
                imz.append(f'Doc_0/Pages/Page_{index}/Content.xml',self.makepagecontent(data=data,py=17.5*7,pageidx=index,islast=islast))
            elif len(_newlistdata) > 36 and len(_newlistdata) <= 40:
                data['datas'] = _newlistdata
                imz.append(f'Doc_0/Tpls/Tpl_{index}/Content.xml',self.maketemplate(data=data,py=17.5*8,islast=islast))
                imz.append(f'Doc_0/Pages/Page_{index}/Content.xml',self.makepagecontent(data=data,py=17.5*8,pageidx=index,islast=islast))
            elif len(_newlistdata) > 40 and len(_newlistdata) <= 42:
                data['datas'] = _newlistdata
                imz.append(f'Doc_0/Tpls/Tpl_{index}/Content.xml',self.maketemplate(data=data,py=17.5*8,islast=islast))
                imz.append(f'Doc_0/Pages/Page_{index}/Content.xml',self.makepagecontent(data=data,py=17.5*8,pageidx=index,islast=islast))
            elif len(_newlistdata) > 42 and len(_newlistdata) <= 47:
                if islast:
                    data['datas'] = _newlistdata[0:41]
                    imz.append(f'Doc_0/Tpls/Tpl_{index}/Content.xml',self.maketemplate(data=data,py=17.5*8,islast=False))
                    imz.append(f'Doc_0/Pages/Page_{index}/Content.xml',self.makepagecontent(data=data,py=17.5*8,pageidx=index,islast=False))
                    data['datas'] = _newlistdata[42:]
                    template_id = self._getid()
                    self.template_ids.append(template_id)
                    templatePages.append(f"""<ofd:TemplatePage ID="{template_id}" BaseLoc="Tpls/Tpl_{i+1}/Content.xml"/>""")
                    pages.append(f"""<ofd:Page ID="{self._getid()}" BaseLoc="Pages/Page_{i+1}/Content.xml"/>""")
                    indexpy += 1
                    imz.append(f'Doc_0/Tpls/Tpl_{index+1}/Content.xml',self.maketemplate(data=data,py=0,islast=True))
                    imz.append(f'Doc_0/Pages/Page_{index+1}/Content.xml',self.makepagecontent(data=data,py=0,pageidx=index+1,islast=True))   
                else:
                    data['datas'] = _newlistdata
                    imz.append(f'Doc_0/Tpls/Tpl_{index}/Content.xml',self.maketemplate(data=data,py=17.5*8+8.75*2,islast=islast))
                    imz.append(f'Doc_0/Pages/Page_{index}/Content.xml',self.makepagecontent(data=data,py=17.5*8+8.75*2,pageidx=index,islast=islast))
            else:
                data['datas'] = _newlistdata
                imz.append(f'Doc_0/Tpls/Tpl_{index}/Content.xml',self.maketemplate(data=data,py=0,islast=islast))
                imz.append(f'Doc_0/Pages/Page_{index}/Content.xml',self.makepagecontent(data=data,py=0,pageidx=index,islast=islast))
        self.templatePages_xml_str = "".join(templatePages)
        self.pages_xml_str = "".join(pages)
        imz.append('Doc_0/Document.xml',self.makedocumentxml())
        imz.append('OFD.xml',self.makeofdxml(data))
        #imz.writetofile('ziptest.ofd')
        return imz

    

if __name__ == "__main__":
    # 发票数据样例
    invoice = {
        'KPLX':'31',
        'GGFMC':'购货yyyyy方名称',
        'GGFSBH':'91320115MA27HYXA46',
        'XHFMC':'上海黄浦区大众养老院',
        'XHFSBH':'91310000767934044Y',
        'FPHM':'24312000000115629364',
        'KPRQ':'2024年04月25日',
        'JSHJ':'800000.00',
        'HJ':'1111111111.00',
        'HJSE':'222222222.00',
        'KPR':'彭清艳',
        'BZ':'''大苏打实打实/r/n的阿德飒飒大苏打撒旦啊实打实大苏打萨达的阿德飒飒大苏打撒旦啊实打实大苏打萨达的阿德飒飒大苏打撒旦啊实打实大苏打萨达的阿德飒飒大苏打撒旦啊实打实大苏打萨达的阿德飒飒大苏打撒旦啊实打实大苏打萨达'''
    }
    datas = [
        {
            'ItemName':'*人力资源服务*劳务1111111111111111111111',
            'SpecMod':'规格型号1',
            'MeaUnits':'单位',
            'Quantity':'2.00',
            'UnPrice':'200000.00',
            'Amount':'400000.00',
            'TaxRate':'6%',
            'ComTaxAm':'24000.00'
        },
        {
            'ItemName':'*人力资源服务*劳务',
            'SpecMod':'规格型号2',
            'MeaUnits':'单',
            'Quantity':'2.00',
            'UnPrice':'200000.00',
            'Amount':'400000.00',
            'TaxRate':'6%',
            'ComTaxAm':'24000.00'
        }
    ]
    for i in range(1,91):
        datas.append({
            'ItemName':'*人力资源服务*劳务',
            'SpecMod':'规格型号2',
            'MeaUnits':'单',
            'Quantity':'2.00',
            'UnPrice':'200000.00',
            'Amount':'400000.00',
            'TaxRate':'6%',
            'ComTaxAm':'24000.00'
        })
    invoice['datas']=datas
    ofd = InvoiceOFD().makeofd(invoice,'shanghai')
    ofd.writetofile('ziptest.ofd')
    
